//
//  HMUserAccount.swift
//  Weibo
//
//  Created by Apple on 2017/7/12.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
//  用户模型的归档和解档路径
let UserAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
//  用户账号模型
class HMUserAccount: NSObject, NSCoding {

    //  令牌
    var access_token: String?
    //  过期秒数
    var expires_in: Int = 0 {
        didSet {
            expiresDate = Date().addingTimeInterval(TimeInterval(expires_in))
        }
    }
    
    //  过期时间
    var expiresDate: Date?
    //  用户id
    var uid: Int64 = 0
    //  用户头像
    var avatar_large: String?
    //  用户名
    var name: String?
    
    //  kvc构造函数
    init(dic: [String: Any]) {
        super.init()
        setValuesForKeys(dic)
    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        aCoder.encode(name, forKey: "name")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
        name = aDecoder.decodeObject(forKey: "name") as? String
    }
    
    
    //  保存用户对象
    func saveUserAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccountPath)
    }
    
    //  解档用户对象
    class func loadUserAccount() -> HMUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: UserAccountPath) as? HMUserAccount
        return userAccount
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        //  空实现
    }
    
}
